package com.example.fileuploader.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;

@Controller
public class UploadFileController {
    @ResponseBody
    @PostMapping(value = "/uploadFolder")
    public String uploadFolder(@RequestParam MultipartFile[] folder) {
        FileUtil.saveMultiFile("/Users/wangyunkun/实验室/server", folder);
        return "success";
    }
}
class FileUtil {

    /**
     * 在basePath下保存上传的文件夹
     * @param basePath
     * @param files
     */
    public static void saveMultiFile(String basePath, MultipartFile[] files) {
        if (files == null || files.length == 0) {
            System.out.println("no files uploaded");
            return;
        }else if (files[0].getOriginalFilename()==null || files[0].getOriginalFilename().equals("")){
            System.out.println("Empty package: no files to be uploaded");
            return;
        }
        if (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        for (MultipartFile file : files) {
            String relativePath = file.getOriginalFilename();
            String filePath = basePath + "/" + relativePath;
            System.out.println("uploading " + relativePath + " to " + filePath + "......");
            makeDir(filePath);
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
                System.out.println("successful upload");
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 确保目录存在，不存在则创建
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }
}


